import { defineComponent, toRefs } from "vue";
import style from "./index.module.less";
import { Col, Row } from "vant";
import { useUploader } from "@/hooks/uploader";
import close from "./asset/close.png";
import { formUploadProps } from "./types";
import * as vant from "vant";
const { showImagePreview } = vant;
import { openPopup } from "./popup";

export default defineComponent({
  name: "upload",
  props: formUploadProps,
  emits: ["change"],
  setup(props, { emit }) {
    return () => {
      const onPreview = (index: number) => {
        // showImagePreview({
        //   images: getValue(),
        //   startPosition: index,
        // });
      };
      const onClose = (e: Event, index: number) => {
        e.stopPropagation();
        e.preventDefault();
        const data = getData();
        data.splice(index, 1);
        emit("change", data);
      };
      const renderListItem = (item: any, index: number) => {
        return (
          <Col class="mt-[10px]">
            <div
              class={["flex flex-col items-center", style.listItem]}
              onClick={() => onPreview(index)}
            >
              <img src={item.path || item.img} />
              <div class={["text-[#666666] mt-[10px]", style.ellipsis]}>
                {item.name}
              </div>
              <img
                class="absolute right-0 top-0 w-[20px] h-[20px]"
                src={close}
                onClick={(e) => onClose(e, index)}
              />
            </div>
          </Col>
        );
      };
      const getData = () => {
        return getValue();
      };
      const renderList = () => {
        return getData().map((e, i) => renderListItem(e, i));
      };
      const getValue = (): any[] => {
        if (Array.isArray(props.modelValue)) {
          return props.modelValue.filter((e) => e);
        } else {
          return [];
        }
      };
      function renderButton() {
        return (
          <Col class="mt-[10px]">
            <div
              class={style.uploadMain}
              onClick={() => {
                openPopup({
                  view: props.item.view,
                  callBack: (data: any) => {
                    const arr = getValue();
                    arr.push(data as never);
                    emit("change", arr);
                  },
                });
              }}
            ></div>
          </Col>
        );
      }
      // 上传接口还没有对接过 所以这边先写个样子
      return (
        <Row gutter={5} class={"mb-[10px]"}>
          {renderList()}
          {renderButton()}
        </Row>
      );
    };
  },
});
